/**
 * 用户历史（我的发文/我的评论/我的喜欢）页面路由
 */

var router = require('express').Router();
var assertAlljs = require('../bin/util/assert-alljs');
var dbentityTool = require('../bin/dbentity');
var ObjectID = require('mongodb').ObjectID;
var userTool = require('../bin/user');
var datetimeTool = require('../bin/util/datetime');

router.get('/userHistory(.*)?', async function(req, res){
    let ses = req.session;
    let assert = assertAlljs(req, res);
    if (await assert(userTool.check(ses.user)))
        return;

    let historys = [];
    let cols = ['article', 'comment'];
    if (req.query.cols!=null){
        if (req.query.cols === ''){
            res.render('dyn.userHistory.html', { historys });
            return;
        }
        cols = req.query.cols.split(',');
    }

    let article_ids = [];

    for (let col of cols){
        let filter = {};
        filter[col === 'fond' ? 'user_id' : 'produceUser._id'] = ses.user._id;
        let docs = await dbentityTool.find(col, filter);
        if (await assert(docs instanceof Error))
            return;
        for (let doc of docs){
            let article_id = doc[col === 'article' ? '_id' : 'article_id'];
            if (col === 'fond')
                doc.brief = '[赞]';
            historys.push({
                type : (col === 'fond' ? '点赞' : (col === 'comment' ? '评论' : '文章')),
                article : article_id,
                time : (col === 'article' ? doc.modifyTime : doc.produceTime),
                item : doc,
            });
            article_ids.push({_id:ObjectID(article_id)});
        }
    }

    if (article_ids.length <= 0){
        res.render('dyn.userHistory.html', { historys });
        return;
    }

    // 获取根板块所有文章列表
    let appendFilter = {};
    if (res.locals.blockRoot)
        appendFilter.mainclass = { $regex: '^'+res.locals.blockRoot+'(/.*)?$' };
    appendFilter.$or = article_ids;

    let articles = await dbentityTool.find('article', appendFilter);
    if (await assert(articles instanceof Error))
        return;
    let articleDic = {};
    articles.forEach(article=>articleDic[article._id]=article);
    historys = historys.filter(history=>history.article in articleDic); // 去掉非当前版块的文章
    historys.forEach(history=>history.article = articleDic[history.article]);

    historys.sort((p1, p2)=>p2.time-p1.time);
    historys.forEach(history=>{ history.time = datetimeTool.to_yMdHm(history.time, '-', ' ', ':');});

    res.render('dyn.userHistory.html', { historys });
});

module.exports = router;